package com.lpf.tomcat;

import org.apache.catalina.core.StandardContext;
import org.apache.catalina.startup.Tomcat;
import org.apache.catalina.startup.Tomcat.FixContextListener;

import com.lpf.servlet.IndexServlet;

/**
 * 使用Java语言创建Tomcat服务器
 * Tomcat 底层执行程序 最终执行servlet
 * SpringMVC底层使用servlet包装
 */
public class JavaTomcat {

    private final static int PORT = 8080;
    private final static String CONTEXT_PATH = "/lpf";
    private final static String SERVLET_NAME = "indexServlet";

    public static void main(String[] args) throws Exception {

        // 创建tomcat服务器
        Tomcat tomcatServer = new Tomcat();
        // 指定端口号
        tomcatServer.setPort(PORT);
        // 是否设置自动部署
        tomcatServer.getHost().setAutoDeploy(false);

        // 创建上下文
        StandardContext standardContex = new StandardContext();
        standardContex.setPath(CONTEXT_PATH);
        // 监听上下文
        standardContex.addLifecycleListener(new FixContextListener());

        // tomcat容器添加standardContex
        tomcatServer.getHost().addChild(standardContex);

        // 创建Servlet
        tomcatServer.addServlet(CONTEXT_PATH, SERVLET_NAME, new IndexServlet());
        // servlet url映射
        standardContex.addServletMappingDecoded("/index", SERVLET_NAME);

        tomcatServer.start();

        System.out.println("tomcat服务器启动成功..");

        // 异步进行接收请求
        tomcatServer.getServer().await();

    }

}
